package com.kevin.Code.Stack;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Vinlee Xiao
 * @Classname BasicCaculator224
 * @Description Leetcode 224. 基本计算器 困难 思路同Leetcode 227
 * @Date 2021/12/11 11:18
 * @Version 1.0
 */
public class BasicCaculator224 {
    public int calculate(String s) {

        String s1 = s.trim();
        int len = s1.length();

        if (len == 0) {
            return 0;
        }
        //最终的结果
        int result = 0;
        //用于存储数字
        char[] ch = s1.toCharArray();
        int index = 0;
        int digit = 0;
        //标记符号正负
        int sign = 1;
        Deque<Integer> operatorDeque = new LinkedList<>();
        operatorDeque.push(sign);

        while (index < len) {
            if (ch[index] == ' ') {
                index++;
            } else if (ch[index] == '+') {
                sign = operatorDeque.peekLast();
                index++;
            } else if (ch[index] == '-') {
                sign = -operatorDeque.peekLast();
                index++;
            } else if (ch[index] == '(') {
                //将左括号之前的符号进入栈中
                operatorDeque.addLast(sign);
                index++;
            } else if (ch[index] == ')') {
                operatorDeque.pollLast();
                index++;
            } else {
                while (index < len && Character.isDigit(ch[index])) {
                    digit = digit * 10 + ch[index] - '0';
                    index++;
                }
                result = result + sign * digit;
                digit = 0;
            }
        }
        return result;
    }
}
